<?php

namespace App\Common\Services;

use Illuminate\Http\Request;
use OSS\Core\OssException;
use OSS\OssClient;
class Upload
{

    public static function uploadToOss(Request $request){
        $accessKeyId=env('ALI_OSS_KEY');
        $accessKeySecret=env('ALI_OSS_SECRET');
        $endpoint=env('ALI_OSS_ENDPOINT');
        $bucket=env('ALI_OSS_BUCKET');
        $file = $request->file('file');
        if($file){
            $filePath=$file->getRealPath();
            $filename='upload/'.date('Ym').'/'.md5($file->getFilename().time().mt_rand(1000,9999)).'.'.$file->getClientOriginalExtension();
            try {
                $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint.'.aliyuncs.com');
                $ossClient->uploadFile($bucket, $filename, $filePath);
            } catch (OssException $e) {
                info('alioss上传失败:'.$e->getMessage().'错误code:'.$e->getCode());
                return ['code' => 1 , 'msg' => '上传失败!!' ];
            }
            return ['code' => 0 , 'msg' => '上传成功' , 'path' =>env('ALI_OSS_URL').$filename,'filename'=>$file->getClientOriginalName()];
        }else{
            return ['code' => 500 , 'msg' => '非法操作' ];
        }

    }




    public static function uploadFile(Request $request)
    {
        $file = $request->file('file');
        if ($file ) {
            if ($file->getSize() > env('FILE_MAX_SIZE')) {
                return ['code' => 1, 'msg' => '上传超出限制'];
            }
            $filename = md5($file->getFilename() . time() . mt_rand(1000, 9999)) . '.' . $file->getClientOriginalExtension();

            $filename=$file->storeAs(date('Ym'),$filename);

            return ['code' => 0, 'msg' => '上传成功', 'path' => '/uploadlocalfile/'.$filename];
        } else {
            return ['code' => 500, 'msg' => '非法操作'];
        }
    }
}
